161D - Distance in Tree - CodeForces Solution


dfs and similar dp trees *1800

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
using LL = long long;
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	int n, k;
	cin >> n >> k;
	vector<vector<int>> e(n + 1);
	for (int i = 0; i < n - 1; i ++ ){
		int u, v;
		cin >> u >> v;
		e[u].push_back(v);
		e[v].push_back(u);
	}
	
	vector<vector<int>> f(n + 1, vector<int>(k + 1));
	int ans = 0;
	function<void(int, int)> dfs = [&](int u, int fa){
		f[u][0] = 1;
		for (auto v : e[u]){
			if (v == fa) continue;
			dfs(v, u);
			for (int i = 0; i < k; i ++ ){
				ans += f[v][i] * f[u][k - i - 1];
			}
			for (int i = 1; i <= k; i ++ ){
				f[u][i] += f[v][i - 1];
			}
		}
	};
	dfs(1, 0);
	cout << ans << "\n";
	return 0;
}


Comments

Submit
0 Comments
More Questions

600C - Make Palindrome
1669D - Colorful Stamp
1669B - Triple
1669A - Division
1669H - Maximal AND
1669E - 2-Letter Strings
483A - Counterexample
3C - Tic-tac-toe
1669F - Eating Candies
1323B - Count Subrectangles
991C - Candies
1463A - Dungeon
1671D - Insert a Progression
1671A - String Building
1671B - Consecutive Points Segment
1671C - Dolce Vita
1669G - Fall Down
4D - Mysterious Present
1316B - String Modification
1204A - BowWow and the Timetable
508B - Anton and currency you all know
1672A - Log Chopping
300A - Array
48D - Permutations
677C - Vanya and Label
1583B - Omkar and Heavenly Tree
1703C - Cypher
1511C - Yet Another Card Deck
1698A - XOR Mixup
1702E - Split Into Two Sets